package com.hxzy.common.feign;


import cn.hutool.core.util.StrUtil;
import com.hxzy.common.consts.UserConstants;
import com.hxzy.common.util.IpUtil;
import com.hxzy.common.util.ServletUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * feign 请求拦截器
 * 
 * @author admin
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor
{
    @Override
    public void apply(RequestTemplate requestTemplate)
    {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (Objects.nonNull(httpServletRequest))
        {
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            // 传递用户信息请求头，防止丢失
            String authentication = headers.get(UserConstants.AUTHORIZATION_HEADER);
            if (StrUtil.isNotBlank(authentication)) {
                requestTemplate.header(UserConstants.AUTHORIZATION_HEADER, authentication);
            }

            // 配置客户端IP
            requestTemplate.header("X-Forwarded-For", IpUtil.getIpAddr(ServletUtils.getRequest()));
        }
    }
}